ReplaceUrl=function(option){
	this.init(option);
};


ReplaceUrl.prototype = {
	store:null,		//db instance
	selector:null,  
	init:function(option){
		this.store = localforage.createInstance({
			"name": option.dbName
		});
		this.selector=option.selector;
		
		window.addEventListener("message", function(e){
			if(e.data.type=="localforageres"){				
			    var URL = window.URL || window.webkitURL;
			    var imgURL = URL.createObjectURL(e.data.imgURL);
				
				$("img[src=\""+e.data.src+"\"]").each(function(){
					$(this)[0].setAttribute("src", imgURL);
				});

			}
		}, false);
		
		this.start();
	},
	getImg:function(key,element){		
		console.log("key",key);
		
		this.store.getItem(key).then(function(blob) {
			
			if(!blob){
				console.log("not find data for key",key);
				return;
			}
			
		    // Get window.URL object
		    var URL = window.URL || window.webkitURL;
		
		    // Create and revoke ObjectURL
		    var imgURL = URL.createObjectURL(blob);
		
		    // Set img src to ObjectURL
		    element.setAttribute("src", imgURL);
		
		    // Revoking ObjectURL
		    element.onload = function() {
		        window.URL.revokeObjectURL(imgURL);
		    }
		});
	},
	postMessage:function(message){
		top.postMessage(message, "*");
	},
	start:function(){
	      // select every nodes we want to rewrite
	      var elements = document.querySelectorAll(
	          this.selector || "img[proxy-img]"
	      );
	      
	      var data = new Array(),message ={"type":"localforage"};
	      
	      $self=this;
	      
	      
	      for (var i=0; i<elements.length; i++) {
	            var element = elements[i];

	            // first we get the element src if it exists...
	            if (!element.src) {
	                 continue;
	            }
	            var src = element.src.trim();

	            // if src is local is not of our concern
	            if (src.match(/^blob:http/i)) {
	                  continue;
	            }
	                
	            var key = src.replace(/^http:\/\//i, '').replace(/\//gm, "-").replace(/\./gm,"-");
	            if(!data[src])data[src]=key;
	            
//		        (function(){
//		            var key = src.replace(/^http:\/\//i, '').replace(/\//gm, "-").replace(/\./gm,"-");
//		            //$self.getImg(key,element);
//		            data[element]=key;
//		        })(element);
	       }
	      	 
	      message.data=data;
	      $self.postMessage(message);
	}	
}
